﻿using M_Purchase.Api.Appliction.Command.AllocateCommand;
using M_Purchase.Repository.PurchaseInterface;
using MediatR;

namespace M_Purchase.Api.Appliction.CommandHandlers.AllocateCommandHandler
{
    /// <summary>
    /// 删除调拨命令处理器
    /// </summary>
    public class DeletedAllocateCommandHandler : IRequestHandler<DeletedAllocateCommand, int>
    {
        /// <summary>
        /// 调拨仓储接口                                                                
        /// </summary>
        protected readonly IAllocateRepository allocateRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="allocateRepository">调拨仓储接口</param>
        public DeletedAllocateCommandHandler(IAllocateRepository allocateRepository)
        {
            this.allocateRepository = allocateRepository;
        }

        /// <summary>
        /// 处理删除调拨命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public async Task<int> Handle(DeletedAllocateCommand request, CancellationToken cancellationToken)
        {
            var result = await allocateRepository.GetModelsAsync(request.AllocateId);
            if (result != null)
            {
                result.IsDeleted = true;
                result.DeletedBy = request.DeletedBy;
                result.DeletedDate = DateTime.Now;
            }
            else
            {
                throw new ArgumentException("该调拨单不存在");
            }
            return await allocateRepository.UpdateAsync(result);
        }
    }
}
